import requests
import time

BASE = "http://localhost:8080"

def create_working_task():
    """创建一个能正常工作的任务来产生日志"""
    
    # 创建 Rabbit → Kafka 任务
    data = {
        "name": "test-r2k-logs",
        "direction": "RABBIT_TO_KAFKA",
        "rabbitSourceHost": "192.168.168.23",
        "rabbitSourcePort": 5672,
        "rabbitSourceVhost": "/",
        "rabbitSourceUsername": "guest",
        "rabbitSourcePassword": "guest",
        "rabbitSourceQueue": "test_queue",  # 我们之前创建的队列
        "rabbitSourcePrefetch": 50,
        "kafkaTargetBootstrap": "192.168.168.23:9092",
        "kafkaTargetTopic": "test_topic",
        "kafkaTargetAcks": "all",
        "enabled": True,
        "concurrency": 1,
        "maxRetries": 3,
        "retryBackoffMs": 1000
    }
    
    response = requests.post(f"{BASE}/api/tasks", json=data)
    if response.ok:
        task = response.json()
        print(f"✓ 创建任务成功: {task['name']} (ID: {task['id']})")
        return task
    else:
        print(f"✗ 创建任务失败: {response.status_code}")
        return None

def start_and_process_messages(task_id):
    """启动任务并处理消息"""
    
    # 启动任务
    response = requests.post(f"{BASE}/api/tasks/{task_id}/start")
    if response.ok:
        print("✓ 任务启动成功")
    else:
        print(f"✗ 任务启动失败: {response.status_code}")
        return
    
    # 等待处理消息
    print("等待消息处理...")
    time.sleep(5)
    
    # 停止任务
    response = requests.post(f"{BASE}/api/tasks/{task_id}/stop")
    if response.ok:
        print("✓ 任务停止成功")
    else:
        print(f"✗ 任务停止失败: {response.status_code}")

def check_logs(task_id):
    """检查日志"""
    
    # 获取日志
    response = requests.get(f"{BASE}/api/logs/{task_id}")
    if response.ok:
        logs = response.json()
        total = logs.get('totalElements', 0)
        print(f"✓ 获取日志成功，共 {total} 条")
        
        if logs.get('content'):
            for i, log in enumerate(logs['content'][:3]):  # 显示前3条
                status = "成功" if log.get('success') else "失败"
                preview = log.get('messagePreview', 'N/A')[:30]
                print(f"  [{i+1}] {log.get('level')} - {log.get('direction')} - {status} - {preview}")
        
        return total > 0
    else:
        print(f"✗ 获取日志失败: {response.status_code}")
        return False

def simulate_error_task():
    """创建一个会产生错误的任务"""
    
    data = {
        "name": "test-error-logs",
        "direction": "KAFKA_TO_RABBIT",
        "kafkaSourceBootstrap": "192.168.168.23:9092",
        "kafkaSourceTopic": "test_topic",
        "kafkaSourceGroup": "test-error-group",
        "kafkaSourceOffsetReset": "latest",
        "rabbitTargetHost": "192.168.168.23",
        "rabbitTargetPort": 5672,
        "rabbitTargetVhost": "/",
        "rabbitTargetUsername": "guest",
        "rabbitTargetPassword": "guest",
        "rabbitTargetExchange": "",
        "rabbitTargetRoutingKey": "nonexistent_error_queue_123",  # 不存在的队列
        "enabled": True,
        "concurrency": 1,
        "maxRetries": 3,
        "retryBackoffMs": 1000
    }
    
    response = requests.post(f"{BASE}/api/tasks", json=data)
    if response.ok:
        task = response.json()
        print(f"✓ 创建错误任务成功: {task['name']} (ID: {task['id']})")
        
        # 启动任务（会产生错误）
        requests.post(f"{BASE}/api/tasks/{task['id']}/start")
        time.sleep(3)
        requests.post(f"{BASE}/api/tasks/{task['id']}/stop")
        
        return task['id']
    else:
        print(f"✗ 创建错误任务失败: {response.status_code}")
        return None

if __name__ == "__main__":
    print("=== 最终功能测试 ===")
    
    # 1. 创建并运行正常任务
    print("\n1. 测试正常任务和日志记录...")
    task = create_working_task()
    if task:
        start_and_process_messages(task['id'])
        has_logs = check_logs(task['id'])
        
        if has_logs:
            print("✓ 日志记录功能正常")
        else:
            print("⚠ 没有产生日志，可能队列中没有消息")
    
    # 2. 创建错误任务
    print("\n2. 测试错误任务...")
    error_task_id = simulate_error_task()
    if error_task_id:
        time.sleep(2)
        check_logs(error_task_id)
    
    # 3. 验证清空错误功能
    print("\n3. 测试清空错误功能...")
    response = requests.get(f"{BASE}/api/tasks")
    if response.ok:
        tasks = response.json()
        for task in tasks:
            if task.get('failed', 0) > 0:
                print(f"发现错误任务: {task['name']}, 失败次数: {task['failed']}")
                
                # 清空错误
                clear_response = requests.post(f"{BASE}/api/tasks/{task['id']}/clear-error")
                if clear_response.ok:
                    print("✓ 清空错误成功")
                else:
                    print("✗ 清空错误失败")
                break
        else:
            print("没有找到有错误的任务")
    
    print("\n=== 测试完成 ===")
    print("现在可以在前端界面测试:")
    print("1. 访问 http://localhost:5173")
    print("2. 查看仪表盘的统计数据")
    print("3. 在任务列表中点击'日志'按钮查看消息日志")
    print("4. 在任务列表中点击'清错'按钮清空错误信息")
    print("5. 测试日志查看器的分页和过滤功能")
